package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.Category.Impl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品分类
 * 主意：添加时的时间和修改时的时间是使用 MyMetaObjecthandler 自动填充的
 * */
@RequestMapping("/category")
@RestController
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryServiceImpl categoryService;

    /**
     * 分类列表查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //分页构造器
        Page pageinfo = new Page(page,pageSize);
        //添加排序构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        //执行查询
        categoryService.page(pageinfo,queryWrapper);
        return R.success(pageinfo);
    }

    /**
     * 添加菜品分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> Categorization(@RequestBody Category category){
        log.info("添加分类信息：{}",category.toString());
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 修改 分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> PutCategorization(@RequestBody Category category){
        log.info("添加分类信息：{}",category.toString());
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    /**
     * 根据 id 进行 删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        log.info("删除商品分类");
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    /**
     * 根据条件查询分类数据
     * @param type
     * @return
     */
    @GetMapping("list")
    public R<List<Category>> list(Category type){
        //条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        lambdaQueryWrapper.eq(type.getType() != null,Category::getType,type.getType());
        //添加排序条件
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }

}
